<template>
  <div id="addQuestionView">
    <el-card class="table-main">
      <template #header>
        <div class="card-header">
          <h2>创建题目</h2>
        </div>
      </template>
      <el-form :model="form" label-width="120px" label-position="right">
        <el-form-item field="title" label="标题">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item field="" label="标题">
          <!--          <el-input v-model="form.difficulty" placeholder="请" />-->
          <el-select
            v-model="form.difficulty"
            class="m-2"
            placeholder="Select"
            size="large"
          >
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>
        <el-form-item field="tags" label="标签" class="form-tag">
          <el-tag
            v-for="tag in form.tags"
            :key="tag"
            class="tag"
            @close="handleClose(tag)"
            placeholder="请选择标签"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            class="ml-1 w-20 inputVisible"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag ml-1"
            size="small"
            @click="showInput"
          >
            + 新增
          </el-button>
        </el-form-item>
        <el-form-item field="content" label="题目内容">
          <MdEditor :value="form.content" :handle-change="onContentChange" />
        </el-form-item>
        <el-form-item field="answer" label="答案">
          <!--          <CodeEditor :value="form.answer as string"></CodeEditor>-->
          <MdEditor
            :value="form.answer as string"
            :handle-change="onAnswerChange"
          />
        </el-form-item>
        <el-form-item
          label="判题配置"
          :content-flex="false"
          :merge-props="false"
        >
          <el-space direction="vertical" style="min-width: 480px">
            <el-form-item field="judgeConfig.timeLimit" label="时间限制">
              <el-input-number
                v-model="form.judgeConfig.timeLimit"
                placeholder="请输入时间限制"
                mode="button"
                :min="0"
                size="large"
              />
            </el-form-item>
            <el-form-item field="judgeConfig.memoryLimit" label="内存限制">
              <el-input-number
                v-model="form.judgeConfig.memoryLimit"
                placeholder="请输入内存限制"
                mode="button"
                :min="0"
                size="large"
              />
            </el-form-item>
            <el-form-item field="judgeConfig.stackLimit" label="堆栈限制">
              <el-input-number
                v-model="form.judgeConfig.stackLimit"
                placeholder="请输入堆栈限制"
                mode="button"
                :min="0"
                size="large"
              />
            </el-form-item>
          </el-space>
        </el-form-item>
        <el-form-item
          label="测试用例配置"
          :content-flex="false"
          :merge-props="false"
        >
          <el-form-item
            v-for="(judgeCaseItem, index) of form.judgeCase"
            :key="index"
            no-style
          >
            <el-space direction="vertical" style="min-width: 640px">
              <el-form-item
                :field="`form.judgeCase[${index}].input`"
                :label="`输入用例-${index}`"
                :key="index"
              >
                <el-input
                  type="textarea"
                  v-model="judgeCaseItem.input"
                  placeholder="请输入测试输入用例"
                />
              </el-form-item>
              <el-form-item
                :field="`form.judgeCase[${index}].output`"
                :label="`输出用例-${index}`"
                :key="index"
              >
                <el-input
                  type="textarea"
                  v-model="judgeCaseItem.output"
                  placeholder="请输入测试输出用例"
                />
              </el-form-item>
              <el-button status="danger" @click="handleDelete(index)">
                删除
              </el-button>
            </el-space>
          </el-form-item>
          <div style="margin-top: 32px">
            <el-button @click="handleAdd" status="success"
              >新增测试用例
            </el-button>
          </div>
        </el-form-item>
        <div style="margin-top: 16px" />
        <el-form-item>
          <el-button
            class="submit-button"
            type="primary"
            style="min-width: 200px"
            @click="doSubmit"
            >提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import MdEditor from '/@/components/MdEditor.vue'
import { ProblemControllerService, ProblemVo } from '../../../generated'
import type { ProblemAddRequest } from '../../../generated'

import { ElInput, ElMessage } from 'element-plus'

import { useRoute } from 'vue-router'

const route = useRoute()
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes('update')

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
const handleInputConfirm = () => {
  if (inputValue.value) {
    form.tags.push(inputValue.value)
  }
  console.log(inputVisible.value)
  console.log(inputValue.value)

  console.log(form.tags)
  inputVisible.value = false
  inputValue.value = ''
}
const handleClose = (tag: string) => {
  console.log(tag)
  console.log(form.tags)
  // form.tags.splice(form.tags.indexOf(tag), 1)
}

let form = reactive({
  uid: 2,
  title: '',
  tags: [],
  answer: '',
  content: '',
  difficulty: '',
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 1000,
    timeLimit: 1000,
  },
  judgeCase: [
    {
      input: '',
      output: '',
    },
  ],
})

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id
  if (!id) {
    return
  }
  const res = await ProblemControllerService.getProblemVoById(id as any)
  if (res.code === 0) {
    form = res.data as any
    // json 转 js 对象
    if (!form.judgeCase) {
      form.judgeCase = [
        {
          input: '',
          output: '',
        },
      ]
    } else {
      form.judgeCase = JSON.parse(form.judgeCase as any)
    }
    if (!form.judgeConfig) {
      form.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,
      }
    } else {
      form.judgeConfig = JSON.parse(form.judgeConfig as any)
    }
    if (!form.tags) {
      form.tags = []
    } else {
      form.tags = JSON.parse(form.tags as any)
    }
  } else {
    ElMessage({
      type: 'error',
      message: '加载失败，' + res.message,
    })
  }
}

onMounted(() => {
  loadData()
})

const router = useRouter()

const doSubmit = async () => {
  console.log(form)
  // 区分更新还是创建
  if (updatePage) {
    const res = await ProblemControllerService.updateProblem(
      form as ProblemAddRequest,
    )
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '更新成功',
      })
    } else {
      ElMessage({
        type: 'error',
        message: '更新失败，' + res.message,
      })
    }
  } else {
    const res = await ProblemControllerService.addQuestion(form)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '创建成功',
      })
    } else {
      ElMessage({
        type: 'error',
        message: '创建失败，' + res.message,
      })
    }
  }

  router.push({
    path: '/home/problemView/',
  })
}

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.judgeCase.push({
    input: '',
    output: '',
  })
}

/**
 * 删除判题用例
 */
const handleDelete = (index: number) => {
  form.judgeCase.splice(index, 1)
}

const onContentChange = (value: string) => {
  console.log('onContentChange' + value)
  form.content = value
}

const onAnswerChange = (value: string) => {
  console.log('onAnswerChange', value)
  form.answer = value
}
</script>

<style scoped>
#addQuestionView {
  width: 80%;
  margin: 10px auto;
  padding: 10px;
}

.table-main {
  width: 100%;
}

.tag {
  margin-right: 10px;
}

.inputVisible {
  margin-top: 10px;
}

.form-tag {
  min-height: 60px;
}

.submit-button {
  margin: 0 auto;
  display: flex;
  //display: inline-block;
}
</style>
